﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Didsoft.Silverlight.ViewModel;
using System.Collections.ObjectModel;
using Didsoft.Silverlight.ViewModel.Commanding.Contracts;

namespace Didsoft.SalesLive.UI.Views.VistaModelo
{
    public class ViewModelBase<T> : BindableObject where T :new() 
    {
        private T selectedItem;
        public T SelectedItem
        {
            get { return selectedItem; }
            set { selectedItem = value; FirePropertyChanged("SelectedItem"); CmdSave.RaiseCanExecuteChanged(); }
        }

        

        private ObservableCollection<T> itemsSource;
        public ObservableCollection<T> ItemsSource
        {
            get { return itemsSource; }
            set { itemsSource = value; FirePropertyChanged("ItemsSource"); }
        }

        public ICommandEvent CmdNew { get; set; }
        public bool CmdNew_CanExecute(object param)
        {
            return SelectedItem == null;
        }
        public void CmdNew_Execute(object param)
        {
            SelectedItem = new T();
            CmdSave.RaiseCanExecuteChanged();

        }

        public ICommandEvent CmdSave { get; set; }
        public bool CmdSave_CanExecute(object param)
        {
            return SelectedItem != null;
        }
        public void CmdSave_Execute(object param)
        {
            context.SubmitChanges(guardado =>
            {
                if (guardado.HasError)
                {
                    MessageBox.Show(guardado.Error.Message);
                    guardado.MarkErrorAsHandled();
                }

            }, null);
        }


        public ICommandEvent CmdDelete { get; set; }
        public bool CmdDelete_CanExecute(object param)
        {
            return param != null;
        }
        public void CmdDelete_Execute(object param)
        {

        }

        public ViewModelBase()
        {
            CmdNew = new DelegateCommand<object>(CmdNew_Execute, CmdNew_CanExecute);
            CmdSave = new DelegateCommand<object>(CmdSave_Execute, CmdSave_CanExecute);
            CmdDelete = new DelegateCommand<object>(CmdDelete_Execute, CmdDelete_CanExecute);           

        }


        public System.ServiceModel.DomainServices.Client.DomainContext context { get; private set; }

        public void SetDomainContext(System.ServiceModel.DomainServices.Client.DomainContext domainContext)
        {
            context = domainContext;
        }
       
    }

}
